<template>
  <div id="app">
    <AppNavbar ref="navbar" />
    <div class="main-content">
      <router-view/>
    </div>
  </div>
</template>
<script>
import AppNavbar from './components/AppNavbar.vue'
import { isTokenExpired } from './utils/jwt'

export default {
  name: 'App',
  components: {
    AppNavbar
  },
  created() {
    // 应用启动时检查token有效性
    this.checkTokenValidity()
  },
  watch: {
    // 监听路由变化，处理登录重定向
    '$route'(to) {
      if (to.query.showLogin === 'true') {
        // 显示登录提示并打开登录弹框
        this.$message.warning('请先登录后再访问该页面')
        this.$nextTick(() => {
          if (this.$refs.navbar) {
            this.$refs.navbar.showAuthModal('login')
          }
        })
      }
    }
  },
  methods: {
    checkTokenValidity() {
      const token = localStorage.getItem('token')
      const user = localStorage.getItem('user')
      
      if (token && user) {
        // 检查token是否过期
        if (isTokenExpired(token)) {
          // token已过期，清除本地存储
          localStorage.removeItem('token')
          localStorage.removeItem('user')
          this.$store.commit('setUser', null)
        } else {
          // token有效，恢复用户状态
          try {
            const userInfo = JSON.parse(user)
            this.$store.commit('setUser', userInfo)
          } catch (error) {
            console.error('解析用户信息失败:', error)
            // 清除无效的用户信息
            localStorage.removeItem('user')
            localStorage.removeItem('token')
          }
        }
      }
    }
  }
}
</script>

<style lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  background: #f7f8fa;
  min-height: 100vh;
}

.container {
  max-width: 960px;
  margin: 16px auto;
  padding: 0 12px;
}

.main-content {
  padding-top: 90px; /* 为固定导航条留出空间 */
  min-height: calc(100vh - 90px);
}
</style>
